package com.ccy.net;

import com.ccy.utils.Log;

/**
 * 单例对象主要便于提交任务，每次任务都是new重新创建的<br>
 * 核心是在new的时候（或init）创建公用对象，如线程池、配置信息等;
 */
public final class WeatherLoader {

	private volatile static WeatherLoader instance;

	private WeatherDownloader mDownloader;
	private WeatherEngine mEngine;

	/** Returns singleton class instance */
	public static WeatherLoader getInstance() {
		if (instance == null) {
			synchronized (WeatherLoader.class) {
				if (instance == null) {
					instance = new WeatherLoader();
				}
			}
		}
		return instance;
	}

	private WeatherLoader() {
	}

	public synchronized void init() {
		if (mDownloader == null || mEngine == null) {
			mDownloader = new WeatherDownloader();
			mEngine = new WeatherEngine();
		} else {
			Log.e("Try to initialize WeatherLoader which had already been initialized before. ");
		}
	}

	public void destroy() {
		stop();
		mDownloader = null;
		mEngine = null;
	}

	private void stop() {
		mEngine.stop();
	}

	public void getWeatherInfo(String city) {
		LoadWeatherTask loadWeatherTask = new LoadWeatherTask(mDownloader, city);
		mEngine.submit(loadWeatherTask);
	}
}
